package com.example.result

import android.Manifest
import android.annotation.SuppressLint
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.result.books.FileFinder
import com.example.result.books.FileOperation
import com.example.result.books.WebViewScreen
import com.example.result.explore.CoroutineExplore
import com.example.result.explore.ExploreScreen
import com.example.result.player.PlayerScreen
import com.example.result.preference.SettingScreen
import com.example.result.ui.theme.AppTheme
import com.example.result.ui.theme.ShouldShowRationalPermissionLocal
import com.lly.tboc.zhouyi.GuaEditScreen
import com.lly.tboc.zhouyi.GuaListScreen
import com.lly.tboc.zhouyi.GuaSearchScreen
import com.lly.tboc.zhouyi.Screen
import com.lly.tboc.zhouyi.YaoScreen
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@AndroidEntryPoint
class MainActivity : BaseActivity() {
    private val routeState = MutableStateFlow("")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AppTheme {
                val navController = rememberNavController()
                val startRoute =
                    if (BuildConfig.isExample) Screen.Books.route else Screen.ZhouYi.route
                NavHost(
                    navController,
                    enterTransition = { slideInHorizontally { 0 } },
                    exitTransition = { slideOutHorizontally { 0 } },
                    startDestination = startRoute
                ) {
                    composable(Screen.CoroutineExplore.route) {
                        var ans by remember {
                            mutableStateOf(emptyList<String>())
                        }
                        LaunchedEffect(key1 = ans.isEmpty()) {
                            withContext(Dispatchers.IO) {
                                ans = CoroutineExplore().result()
                            }
                        }
                        LazyColumn {
                            items(ans) {
                                Card {
                                    Text(text = it)
                                }
                                HorizontalDivider(Modifier.padding(8.dp))
                            }
                        }
                    }
                    composable(
                        Screen.GuaSearch.route,
                    ) {
                        GuaSearchScreen(
                            Screen.GuaSearch.keyword(it, ""),
                            onDismissRequest = { navController.popBackStack() },
                            scrollToGua = {
                                navController.navigate(Screen.ZhouYi.guaRoute(it)) {
                                    launchSingleTop = true
                                }
                            })
                    }
                    composable(Screen.ZhouYi.route, Screen.ZhouYi.arguments) { backStackEntry ->
                        val guaId = Screen.ZhouYi.guaId(backStackEntry, -1)
                        GuaListScreen(
                            guaId,
                            navController,
                            { gua -> navController.navigate(Screen.Yao.yaoRoute(gua.id)) },
                            { gua ->
                                navController.navigate(
                                    Screen.GuaEdit.editRoute(
                                        gua.id
                                    )
                                )
                            },
                        ) {
                            if (!navController.popBackStack()) {
                                finish()
                            }
                        }
                    }
                    composable(Screen.Books.route) {
                        ShouldShowRationalPermissionLocal.current.readStorage.value =
                            shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)
                        ShouldShowRationalPermissionLocal.current.fileManager.value =
                            shouldShowRequestPermissionRationale(Manifest.permission.MANAGE_EXTERNAL_STORAGE)
                        FileFinder()
                    }
                    composable(
                        Screen.WebView.route,
                    ) { backStackEntry ->
                        Surface(color = MaterialTheme.colorScheme.primary.copy(alpha = 0.7f)) {
                            WebViewScreen(
                                Modifier,
                                com.lly.tboc.zhouyi.Screen.WebView.FileAddress.Uri(intent.data!!),
                                object : FileOperation {
                                    override fun saveToFile(content: String, name: String) {
                                        Toast.makeText(
                                            applicationContext,
                                            "当前位置不支持保存",
                                            Toast.LENGTH_SHORT
                                        ).show()
                                    }

                                    override fun shareFile(context: Context, path: String) {
                                        Toast.makeText(
                                            applicationContext,
                                            "当前位置不支持分享",
                                            Toast.LENGTH_SHORT
                                        ).show()
                                    }

                                    override fun uploadFile(path: String) {
                                        Toast.makeText(
                                            applicationContext,
                                            "当前位置不支持",
                                            Toast.LENGTH_SHORT
                                        ).show()
                                    }
                                })
                        }
                    }
                    composable(Screen.Setting.route) {
                        SettingScreen(modifier = Modifier)
                    }
                    composable(
                        Screen.GuaEdit.route,
                        arguments = Screen.GuaEdit.guaEditRouteArguments
                    ) { backStackEntry ->
                        GuaEditScreen(
                            guaId = Screen.GuaEdit.guaId(backStackEntry, 1),
                            navController = navController
                        )
                    }
                    composable(
                        Screen.Yao.route,
                        arguments = Screen.Yao.yaoRouteArguments
                    ) { backStackEntry ->
                        YaoScreen(
                            navController,
                            Screen.Yao.guaId(backStackEntry, 1)
                        )
                    }
                    composable(Screen.Explore.route) {
                        ExploreScreen()
                    }
                    composable(
                        Screen.Audio.route,
                        arguments = Screen.Audio.arguments
                    ) {
                        /* var canShow by remember {
                             mutableStateOf(false)
                         }*/
                        PlayerScreen(intent.data!!)
                    }
                }
                rememberCoroutineScope().launch {
                    routeState.filter { it.isNotEmpty() }.collect {
                        navController.navigate(routeState.value)
                        routeState.value = ""
                    }
                }
            }
        }
        handleIntent()
    }

    private fun handleIntent() {
        Log.e("handleIntent", "intent.scheme:${intent?.scheme}")
        intent?.let { intent ->
            if (arrayOf("audio/", "video/").any { intent.type?.startsWith(it) == true }) {
                routeState.value = Screen.Audio.route(intent.data)
            } else if (Intent.ACTION_SEARCH == intent.action) {
                intent.getStringExtra(SearchManager.QUERY)?.also { query ->
                    routeState.value = Screen.GuaSearch.searchRoute(query)
                }
            } else if (arrayOf("content", "file").any { intent.scheme.equals(it) }) {
                routeState.value = Screen.WebView.route
            } else {

            }
        }
    }

    @SuppressLint("MissingSuperCall")
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        handleIntent()
    }
}
